package com.example.util;

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {
    static final String ALGORITHM = "AES";

    // 生成一个key
    public static SecretKey secretKey() throws NoSuchAlgorithmException {
        KeyGenerator keygenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom securerandom = new SecureRandom();
        keygenerator.init(securerandom); //对密钥生成器进行初始化，将随机数生成器传进去
        SecretKey secretkey = keygenerator.generateKey(); //生成key
        return secretkey;
    }

    // 加密方法
    public static byte[] encrypt(byte[] fileBytes, SecretKey secretkey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretkey);
        byte[] result = cipher.doFinal(fileBytes);
        // 使用Base64不然会出现乱码
        byte[] encode = Base64.getEncoder().encode(result);
        return encode;
    }

    // 解密方法
    public static byte[] decrypt(byte[] contentArray, SecretKey secretkey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretkey);

        // 使用Base64不然会出现乱码
        byte[] decode = Base64.getDecoder().decode(contentArray);
        byte[] result = cipher.doFinal(decode);
        return result;
    }
}
